package org.mili.ticketeer.dao;

import org.mili.application.dao.AbstractDao;
import org.mili.application.dao.DaoException;
import org.mili.application.dao.ModificationResult;
import org.mili.application.dao.RowTransformer;
import org.mili.application.dao.query.QueryBuilder;
import org.mili.ticketeer.dto.Action;
import org.mili.application.dto.Identifieable;
import org.mili.ticketeer.dto.Ticket;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class ActionDao extends AbstractDao {

    public ActionDao() {
        super(Action.UniqueFields.values(), Action.Fields.values(), Action.TABLE);
    }

    public ModificationResult write(final Action action) throws DaoException {
        return createOrUpdate(action);
    }

    public List<Action> getActionsFor(final Ticket ticket) throws DaoException {
        return read(new RowTransformer<Action>() {
                @Override
                public Action transform(ResultSet resultSet) throws SQLException {
                    Action action = new Action();
                    action.setId(resultSet.getInt(Identifieable.Fields.ID.name()));
                    action.setTicket(resultSet.getInt(Action.Fields.TICKET.name()));
                    action.setComment(resultSet.getString(Action.Fields.COMMENT.name()));
                    action.setTitle(resultSet.getString(Action.Fields.TITLE.name()));
                    action.setDate(resultSet.getTimestamp(Action.Fields.DATE.name()));
                    return action;
                }
            }, QueryBuilder.createQueryBuilder()
                    .select()
                    .fields(Identifieable.Fields.ID, Action.Fields.values())
                    .from(Action.TABLE)
                    .where()
                    .eq(Action.Fields.TICKET, ticket.getId())
                    .orderBy()
                    .asc(Action.Fields.DATE)
                    .build()
            );
    }

}
